package com.tyx.chargingpile.job;

import com.tyx.chargingpile.cache.SocketChannelMap;
import com.tyx.chargingpile.config.NettyConfig;
import com.tyx.chargingpile.vo.PileInfo;
import com.tyx.chargingpile.util.DateUtils;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

@Component
@Configuration
@EnableScheduling
public class HeartJob {

    private final static Logger LOGGER = LoggerFactory.getLogger(HeartJob.class);


    @Scheduled(cron = "0 0/2 * * * ? ")
    private void configureTasks() {
        LOGGER.info("开始心跳扫描.....");
        Date nowDate = DateUtils.now();
        Map<String,String> map = SocketChannelMap.getChannelMapperMap();
        if(map != null) {
            synchronized (map) {
                Set<Map.Entry<String, String>> set = map.entrySet();
                Iterator<Map.Entry<String, String>> iterator = set.iterator();
//                map.forEach((k, v) -> {
                while (iterator.hasNext()) {
                    Map.Entry<String, String> entry=iterator.next();
                    String k = entry.getKey();
                    String v = entry.getValue();
                    PileInfo pileInfo = SocketChannelMap.getPileInfo(k);
                    if (pileInfo != null) {
                        Long interval = nowDate.getTime() - pileInfo.getLastSurvivalTime().getTime();
                        if (interval > 120000) {
                            // TODO: 2019/4/20 超时
                            ChannelHandlerContext channelHandlerContext = (ChannelHandlerContext) SocketChannelMap.getChanneLContext(v);
                            NettyConfig.group.remove(channelHandlerContext.channel());
                            SocketChannelMap.heartRemoveChannelMap(pileInfo.getDevice_id());
                            iterator.remove();
                            channelHandlerContext.close();
                            LOGGER.info("通道：" + k + "连接超时已移除" + "设备：" + pileInfo.getDevice_id());
                        }
                    }
                }
//                });
            }
        }
        int connetCount = NettyConfig.group.size();
        LOGGER.info("链接数"+connetCount+".....");
        LOGGER.info("结束心跳扫描.....");
    }
}
